layui.define(['layer', 'form','jquery','eleTree'], function(exports){
        var layer = layui.layer //弹层
        ,$ = layui.jquery
        ,eleTree = layui.eleTree
        ,form = layui.form;
//界面分为左侧菜单树和右侧菜单详情。然后根据左边菜单树的节点选择，再更新右侧的菜单表单详情，
//     ——》 初始化菜单树   ——》 选取树节点——》    得到节点数据data
//              ——》    表单组件监控 type是 菜单？权限   ——》  重新渲染赋值表单详情
//

//把获取的节点信息做成全局变量
var node_data=null;
var el = null;
var MOD_NAME="sysMenu";
var sysMenu = {

    // 初始化菜单树
    init_tree:function ( expandNodeKey) {
        el= eleTree.render({
            elem: '.roleTree',
            url: '/system/selectMenuAndPermTree',
            showCheckbox: false,
            defaultExpandedKeys:[expandNodeKey],
            contextmenuList: ['add','remove'],
            request: {

                key: "permissionId",
                name: "title",
                children: "children",
                checked: "checked",
                disabled: "disabled",
                isLeaf: "isLeaf",

                sortNumber: "sortNumber",
                type: "type",
                pid: "parentId",
            },
            response: {
                statusName: "code",
                statusCode: 200,
                dataName: "data"
            }
        });
    },

    // 树节点点击事件
    choose_tree:function(){
        eleTree.on("nodeClick(role_tree_data)",function(node) {

            $("#add_perm_from").hide();
            $("#edit_perm_form").hide();

            node_data = null;
            node_data =node.data.currentData;
            let isNewLab = node_data.isNewLab;

            sysMenu.choose_form(node_data.type);
            sysMenu.change_form_read_or_edit("read");
            console.log(node_data);
        });
    },

    // 右侧菜单
    //       功能1 添加时候选取添加权限类型   显示表单
    //       功能2 查看时候根据传入的权限类型 显示表单
    choose_form:function(type){
        form.on('radio(add_type)', function(data){
            if(data.value === "1"){ //1菜单 2权限
                $("#add_code").hide();
                $("#add_meun").show();
            }else{
                $("#add_code").show();
                $("#add_meun").hide();
            }

        });

        if (type!==undefined) {

            if(type === 1){
                $("#add_code").hide();
                $("#add_meun").show();

            }else{
                $("#add_code").show();
                $("#add_meun").hide();

            }

        }

    },

    // 根据树节点信息 重新渲染表单
    show_perm_List:function(data){
        form.val("perm_form",{    //form.val('filter', object); 表单赋值和取值，这里赋值；
            //如果 object 参数存在，则为赋值；如果 object 参数不存在，则为取值
            "permission_id" : data.permissionId, //表格赋值操作 k为表单中的name ,v为渲染表格字段
            "title": data.title,
            "type": data.type,
            "parent_id": data.parentId,
            "sort_number" : data.sortNumber,
            "href_method" : data.hrefMethod,
            "icon": data.icon,
            "href": data.href,
            "spread":data.spread,
            "code": data.code,
            "enable" : data.enable

        });

    },

    // 添加 编辑 删除 按钮事件
    button_listen:function () {
        // 添加
        $("#add_perm").click(function () {

            $("#add_perm_from").show();
            $("#edit_perm_form").hide();
            sysMenu.change_form_read_or_edit("add");

            var historyParentId = $("#parent_id").val();
            $("#perm_form")[0].reset();  //添加清空表格用法
            form.val("perm_form",{    //form.val('filter', object); 表单赋值和取值，这里赋值；
                "parent_id" :historyParentId
            });
            form.render();
            form.on('submit(add_perm_form)', function(data) {//REST风格 function(data) 因为submit监听了submitTable表单，data代表的是表单中的整体对象

                if(data.field.enable === "on") {
                    data.field.enable = "1";
                } else {
                    data.field.enable = "0";
                }

                if(data.field.spread === "on") {
                    data.field.spread = "1";
                } else {
                    data.field.spread = "0";
                }
                console.log(data);


                $.ajax({
                    type: "POST",
                    contentType:"application/json",//设置请求参数类型为json字符串
                    url: "/system/permission",
                    data: JSON.stringify({
                        title: data.field.title,        //这里的data.field 的 title 对应的是html的id
                        type: data.field.type,
                        parentId: data.field.parent_id,
                        sortNumber: data.field.sort_number,
                        icon: data.field.icon,
                        hrefMethod: data.field.href_method,
                        href: data.field.href,
                        spread:data.field.spread,
                        code: data.field.code,
                        enable: data.field.enable
                    }),
                    success:function(resp){
                        var code = resp.code;
                        if (code === 200 ){
                            sysMenu.init_tree();
                            $("#add_perm_from").hide();
                            $("#edit_perm_form").show();
                            sysMenu.change_form_read_or_edit("edit");
                            layer.msg('添加成功', {icon: 1});

                        }else {
                            layui.form.render();
                            layer.msg("添加失败"+ " "+ resp.msg, {icon: 5});
                        }
                    }
                });

                return false;
            });


        });

        $("#edit_perm").click(function () {
            $("#add_perm_from").hide();
            $("#edit_perm_form").show();

            sysMenu.change_form_read_or_edit("edit");


            form.on('submit(edit_perm_form)', function(data) {
                //REST风格 function(data) 因为submit监听了submitTable表单，data代表的是表单中的整体对象
                //data.field 代表表单的每个输入框数据
                if(data.field.enable === "on") {
                    data.field.enable = "1";
                } else {
                    data.field.enable = "0";
                }
                if(data.field.spread === "on") {
                    data.field.spread = "1";
                } else {
                    data.field.spread = "0";
                }
                $.ajax({
                    type: "PUT",
                    contentType:"application/json",//设置请求参数类型为json字符串
                    url: "/system/permission/"+data.field.permission_id,
                    data: JSON.stringify({
                        title: data.field.title,        //这里的data.field 的 title 对应的是html的id
                        type: data.field.type,
                        parentId: data.field.parent_id,
                        sortNumber: data.field.sort_number,
                        icon: data.field.icon,
                        hrefMethod: data.field.href_method,
                        href: data.field.href,
                        spread:data.field.spread,
                        code: data.field.code,
                        enable: data.field.enable
                    }),
                    success:function(resp){
                        var code = resp.code;
                        if (code === 200 ){
                            layer.msg('修改成功', {icon: 1});
                            sysMenu.init_tree();
                        }else {
                            layer.msg("添加失败", {icon: 5});
                        }
                    }
                });
                return false;
            })



        });

        //删除
        $("#deleted_perm").click(function () {
            layer.confirm('是否确定删除选中的数据',
                {
                    icon:0,
                    title: "提示",
                    skin: "deleteTips"
                }
                , function(){

                    var keyArr = '';
                    var data = node_data;
                    if (data===undefined||data ===null){
                        layer.msg('请选择要删除的节点', {icon: 5});
                    }else {

                        //删除单节点
                        if (data.children===null){
                            keyArr = keyArr + data.permissionId;
                        }

                        // 删除含有节点树节点
                        else {

                            keyArr = keyArr + data.permissionId;
                            $.each(data.children,function (index, val) { //index是数组对象索引，val是对象
                                if (index===0){
                                    keyArr = keyArr  +','+ val.permissionId;
                                }else {
                                    keyArr = keyArr +','+ val.permissionId;
                                }
                            });
                        }



                        console.log(keyArr);
                        $.ajax({
                            type: "POST",
                            contentType:"application/x-www-form-urlencoded",//设置请求参数类型为json字符串
                            url: "/system/permissionByBatchDelete",
                            data:{
                                ids: keyArr
                            },
                            success:function(resp){
                                var code = resp.code;
                                if (code === 200 ){
                                    layer.msg('删除成功', {icon: 1});
                                    sysMenu.init_tree();
                                }else {
                                    layer.msg("删除失败", {icon: 5});
                                }
                            }
                        });
                    }



                });
        });
    },


    // 先把禁用状态 更改 会导致标签中信息中丢失，根据全局变量的node_data信息重新渲染表格
    change_form_read_or_edit:function (event) {
        if (event === "add") {
            $("#title").remove();
            $("#title_from").append( "<input  type=" +"text"+ " id = " +"title"+ " name=" +"title"+ "  required  lay-verify="+"required"+"  autocomplete="+"off"+" class="+"layui-input "+">");

            $("#href").remove();
            $("#href_from").append( "<input  type=" +"text"+ " id = " +"href"+ " name=" +"href"+ "  autocomplete="+"off"+" class="+"layui-input "+">" );

            $("#icon").remove();   //菜单图标
            $("#icon_from").append( "<input  type=" +"text"+ " id = " +"icon"+ " name=" +"icon"+ "  autocomplete="+"off"+" class="+"layui-input "+">");

            $("#sort_number").remove();   //排序号
            $("#sort_number_form").append( "<input  type=" +"text"+ " id = " +"sort_number"+ " name=" +"sort_number"+ "  autocomplete="+"off"+" class="+"layui-input "+">" );

            $("#code").remove();   //权限代码
            $("#code_form").append( "<input  type=" +"text"+ " id = " +"code"+ " name=" +"code"+ "  autocomplete="+"off"+" class="+"layui-input "+">");

            $("#add_perm_from").show();
            $("#edit_perm_form").hide();

            var historyParentId = $("#parent_id").val();
            $("#perm_form")[0].reset();  //添加清空表格用法
            form.val("perm_form",{    //form.val('filter', object); 表单赋值和取值，这里赋值；
                "parent_id" :historyParentId
            });
            form.render();
            form.on('submit(add_perm_form)', function(data) {//REST风格 function(data) 因为submit监听了submitTable表单，data代表的是表单中的整体对象

                if(data.field.enable === "on") {
                    data.field.enable = "1";
                } else {
                    data.field.enable = "0";
                }

                if(data.field.spread === "on") {
                    data.field.spread = "1";
                } else {
                    data.field.spread = "0";
                }
                console.log(data);


                $.ajax({
                    type: "POST",
                    contentType:"application/json",//设置请求参数类型为json字符串
                    url: "/system/permission",
                    data: JSON.stringify({
                        title: data.field.title,        //这里的data.field 的 title 对应的是html的id
                        type: data.field.type,
                        parentId: data.field.parent_id,
                        sortNumber: data.field.sort_number,
                        icon: data.field.icon,
                        hrefMethod: data.field.href_method,
                        href: data.field.href,
                        spread:data.field.spread,
                        code: data.field.code,
                        enable: data.field.enable
                    }),
                    success:function(resp){
                        var code = resp.code;
                        if (code === 200 ){
                            sysMenu.init_tree();
                            $("#add_perm_from").hide();
                            $("#edit_perm_form").show();
                            sysMenu.change_form_read_or_edit("edit");
                            layer.msg('添加成功', {icon: 1});

                        }else {
                            layui.form.render();
                            layer.msg("添加失败"+ " "+ resp.msg, {icon: 5});
                        }
                    }
                });

                return false;
            });


            sysMenu.show_perm_List(node_data);
            form.render(); //更新全部
        }
        if (event==="edit"){

            $("#title").remove();
            $("#title_from").append( "<input  type=" +"text"+ " id = " +"title"+ " name=" +"title"+ " required  lay-verify="+"required"+" autocomplete="+"off"+" class="+"layui-input"+" >" );

            $("#href").remove();
            $("#href_from").append( "<input  type=" +"text"+ " id = " +"href"+ " name=" +"href"+ "  autocomplete="+"off"+" class="+"layui-input"+" >" );

            $("#icon").remove();   //菜单图标
            $("#icon_from").append( "<input  type=" +"text"+ " id = " +"icon"+ " name=" +"icon"+ "  autocomplete="+"off"+" class="+"layui-input"+" >" );

            $("#sort_number").remove();   //排序号
            $("#sort_number_form").append( "<input  type=" +"text"+ " id = " +"sort_number"+ " name=" +"sort_number"+ "  autocomplete="+"off"+" class="+"layui-input"+" >" );


            $("#code").remove();   //权限代码
            $("#code_form").append( "<input  type=" +"text"+ " id = " +"code"+ " name=" +"code"+ "  autocomplete="+"off"+" class="+"layui-input"+" >" );


            sysMenu.show_perm_List(node_data);
            form.render(); //更新全部



        }
        if (event==="read") {
            $("#title").remove();
            $("#title_from").append( "<input  type=" +"text"+ " id = " +"title"+ " name=" +"title"+ "  required  lay-verify="+"required"+"  autocomplete="+"off"+" class="+"layui-input"+ " "+"disabled"+">" );

            $("#href").remove();
            $("#href_from").append( "<input  type=" +"text"+ " id = " +"href"+ " name=" +"href"+ "  autocomplete="+"off"+" class="+"layui-input "+" "+"disabled"+">" );

            $("#icon").remove();   //菜单图标
            $("#icon_from").append( "<input  type=" +"text"+ " id = " +"icon"+ " name=" +"icon"+ "  autocomplete="+"off"+" class="+"layui-input "+" "+"disabled"+">" );

            $("#sort_number").remove();   //排序号
            $("#sort_number_form").append( "<input  type=" +"text"+ " id = " +"sort_number"+ " name=" +"sort_number"+ "  autocomplete="+"off"+" class="+"layui-input "+" "+"disabled"+">" );

            $("#code").remove();   //权限代码
            $("#code_form").append( "<input  type=" +"text"+ " id = " +"code"+ " name=" +"code"+ "  autocomplete="+"off"+" class="+"layui-input"+" "+"disabled"+">" );

            sysMenu.show_perm_List(node_data);
            form.render(); //更新全部
        }

    },


    add_child_menu_tree:function () {
        $(".layui-btn layui-btn-sm").click(function(){
            nowIndex = layer.open(  //弹出层
                {
                    type_menu: 1,
                    title: '添加权限页面',

                    area: ['700px', '400px'],
                    btnAlign: 'c',//按钮居中对齐
                    content: $("#add_menu_form"), //选择表单的html Id
                    anim: 5,//弹出效果 渐显
                    success:function(index){
                        $.ajax({
                            url: '/system/permission/getParentNode',
                            dataType: 'json',
                            type: 'GET',
                            success: function (resp) {
                                if (resp.code_menu===200){
                                    var data = resp.data;
                                    $('#parent_menu_id').html('');
                                    $('#parent_menu_id').append("<option value='0'>请选择</option>");// 下拉菜单里添加元
                                    $.each(data, function (index, val) {
                                        $('#parent_menu_id').append("<option value="+val.permissionId+">"+val.title_menu+"</option>");// 下拉菜单里添加元素
                                    });
                                    layui.form.render("select");
                                }else {
                                    $('#parent_menu_id').html('');
                                    $('#parent_menu_id').append("<option value=''>请选择</option>");// 下拉菜单里添加元
                                }

                            }
                        });
                    }
                });
            form.on('radio(add_perm_menu)', function(data){
                console.log(data.value);
                if(data.value === "1"){ //2权限
                    $("#add_code_menu").hide();
                    $("#add_meun_menu").show();
                }else{
                    $("#add_code_menu").show();
                    $("#add_meun_menu").hide();
                }
                form.render();
            });
            form.on('submit(add_submitTable_menu)', function(data) {//REST风格 function(data) 因为submit监听了submitTable表单，data代表的是表单中的整体对象
                if(data.field.enable_menu === "on") {
                    data.field.enable_menu = "1";
                } else {
                    data.field.enable_menu = "0";
                }

                if(data.field.spread_menu === "on") {
                    data.field.spread_menu = "1";
                } else {
                    data.field.spread_menu = "0";
                }

                $.ajax({
                    type_menu: "POST",
                    contentType:"application/json",//设置请求参数类型为json字符串
                    url: "/system/permission",
                    data: JSON.stringify({
                        title_menu: data.field.title_menu,        //这里的data.field 的 title_menu 对应的是html的id
                        type_menu: data.field.type_menu,
                        parentId: data.field.parent_menu_id,
                        sortNumber: data.field.sort_number_menu,
                        icon_menu: data.field.icon_menu,
                        hrefMethod: data.field.href_method_menu,
                        href: data.field.href_menu,
                        spread:data.field.spread_menu,
                        code_menu: data.field.code_menu,
                        enable: data.field.enable_menu
                    }),
                    success:function(resp){
                        var code = resp.code_menu;
                        if (code=== 200 ){

                            $("#add_perm_menu")[0].reset();  //添加清空表格用法
                            layui.form.render();
                            layer.close(nowIndex);

                            layer.msg('添加成功', {icon: 1});
                            tableInfo.reload();
                        }else {
                            layui.form.render();
                            layer.msg("添加失败"+ " "+ resp.msg, {icon: 5});
                        }
                    }
                });
                return false;
            });

        });
    },

    /*
     * 监听菜单右键添加 节点 删除节点事件
     */
    listen_tree_event:function(){

        // 添加节点之前事件
        eleTree.on("nodeInsertBefore(role_tree_data)",function(d) {
            sysMenu.addChildTree(d,1);
        });
        // 添加节点之后事件
        eleTree.on("nodeInsertAfter(role_tree_data)",function(d) {
            sysMenu.addChildTree(d,1);
        });

        // 添加该节点的节点事件
        eleTree.on("nodeAppend(role_tree_data)",function(d) {
            sysMenu.addChildTree(d,3);
        });

        // 节点被删除事件
        eleTree.on("nodeRemove(role_tree_data)",function(obj) {
            // 取消删除
            obj.stop();
            var data = obj.data;
            layer.confirm('是否确定删除节点[ '+data.title + ' ]',
                {
                    icon:0,
                    title: "提示",
                    skin: "deleteTips"
                }
                , function(){

                    var keyArr = '';
                    if (data===undefined||data ===null){
                        layer.msg('请选择要删除的节点', {icon: 5});
                    }else {
                        //删除单节点
                        if (data.children===null){
                            keyArr = keyArr + data.permissionId;
                        }

                        // 删除含有节点树节点
                        else {

                            keyArr = keyArr + data.permissionId;
                            $.each(data.children,function (index, val) { //index是数组对象索引，val是对象
                                if (index===0){
                                    keyArr = keyArr  +','+ val.permissionId;
                                }else {
                                    keyArr = keyArr +','+ val.permissionId;
                                }
                            });
                        }
                        console.log(keyArr);
                        $.ajax({
                            type: "POST",
                            contentType:"application/x-www-form-urlencoded",//设置请求参数类型为json字符串
                            url: "/system/permissionByBatchDelete",
                            data:{
                                ids: keyArr
                            },
                            success:function(resp){
                                var code = resp.code;
                                if (code === 200 ){
                                    layer.msg('删除成功', {icon: 1});
                                    sysMenu.init_tree();
                                }else {
                                    layer.msg("删除失败", {icon: 5});
                                }
                            }
                        });
                    }



                });
        })
    },

    /*
     * 发送添加子节点请求到后台
     */
    addChildTree:function(d,newlabe){
        let sameNodeData = d.data;
        let type = sameNodeData.type;
        let parentId = d.newData.parentId;
        let title =  d.newData.title;
        let sortNumber = sameNodeData.sortNumber;
        let pid;
        if (newlabe===1){
            pid = sameNodeData.parentId;
            sortNumber -= 1;
        }else if (newlabe === 2 ){
            pid = sameNodeData.parentId;
            sortNumber += 1;
        }else if (newlabe === 3 ){
            pid = sameNodeData.permissionId;
            sortNumber = 99;
        }
        d.setData({
            permissionId: "",
            parentId: pid,
            type: type,
            sortNumber: sortNumber,
        });
        $.ajax({
            type: "POST",
            contentType:"application/json",//设置请求参数类型为json字符串
            url: "/system/permission",
            data: JSON.stringify({
                parentId: pid,
                title:  title,
                type: type,
                sortNumber: sortNumber

            }),
            success:function(resp){
                var code = resp.code;
                if (code === 200 ){
                    var resultData = resp.data;
                    $("#add_perm_from").hide();
                    $("#edit_perm_form").show();
                    sysMenu.change_form_read_or_edit("edit");
                    layer.msg('添加成功', {icon: 1});
                    let addPermId = resultData.addPermId;
                    sysMenu.init_tree(addPermId);
                }else {
                    layui.form.render();
                    layer.msg("添加失败"+ " "+ resp.msg, {icon: 5});
                }
            }
        });
    },

};

    sysMenu.add_child_menu_tree();
    sysMenu.init_tree();
    sysMenu.choose_tree();
    sysMenu.choose_form();
    sysMenu.button_listen();
    sysMenu.listen_tree_event();

    /*
     * 参数1 模块名 ；2回调函数
     */
    exports(MOD_NAME,sysMenu);

});